package com.sunyur.tailor.channel.common.middle.handler;

import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.util.ChannelResultUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @Author 99288
 * @Description 全局异常类
 * @Date 15:06 2020/9/29
 * @Param
 * @return
**/
@Log4j2
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     *
     * @Author 99288
     * @Description javax.validator 错误异常
     * @Date 15:15 2020/9/29
     * @Param
     * @return
    **/
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ChannelResult validExceptionHandler(MethodArgumentNotValidException e){
        List<FieldError> fieldErrors=e.getBindingResult().getFieldErrors();
        String message = fieldErrors.stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(","));
        return ChannelResultUtil.error(String.valueOf(HttpServletResponse.SC_BAD_REQUEST), message);
    }

    /**
     * 捕获全局为匹配的异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ChannelResult exceptionHandler(HttpServletRequest req, Exception e) {
        log.info("GlobalExceptionHandler ExceptionHandler Host:{} url:{} ERROR:{}", req.getRemoteHost(), req.getRequestURL(), e);
        return ChannelResultUtil.error(String.valueOf(HttpServletResponse.SC_BAD_REQUEST), e.getMessage());
    }

    /**
     * 参数校验异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ChannelResult bindExceptionHandler(HttpServletRequest req, Exception e) {
        log.info("GlobalExceptionHandler BindExceptionHandler Host:{} url:{} ERROR:{}", req.getRemoteHost(), req.getRequestURL(), e);
        return ChannelResultUtil.error(String.valueOf(HttpServletResponse.SC_BAD_REQUEST), e.getMessage());
    }
}
